import sys
import json
from PyQt5.QtWidgets import (QApplication, QPushButton, QWidget)
from PyQt5 import QtCore, QtWidgets
from ui import ui_chat
import pathlib

class Window(QWidget):
    def __init__(self):
        #self.ui = uic.loadUi(pathlib.Path(__file__).resolve().parent.joinpath('ui').joinpath('chat.ui'))
        super().__init__()
        self.ui = ui_chat.Ui_Form()
        self.ui.setupUi(self)

        # sendButton
        self.ui.sendButton.clicked.connect(self.inputEnter)

        # tableWidget
        self.ui.tableWidget.setColumnCount(1)
        self.ui.tableWidget.setRowCount(0)
        self.ui.tableWidget.setHorizontalHeaderLabels(["昵称"])
        # self.ui.tableWidget.resizeColumnsToContents()
        # self.ui.tableWidget.resizeRowsToContents()
        self.ui.tableWidget.setColumnWidth(0, 231)
        self.ui.tableWidget.setAlternatingRowColors(True)
        self.ui.tableWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.ui.tableWidget.verticalHeader().setVisible(False)

        item = QtWidgets.QTableWidgetItem()
        self.ui.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()

        # reload people
        self.getFriendList()
    
    def inputEnter(self):
        msg = self.ui.write_text.toPlainText()
        if not msg.strip(): return
        username = "<font color=\"#FF0000\">alonescar:</font>"
        msg = "  " + msg
        # 73
        self.ui.chatEdit.append(username)
        self.ui.chatEdit.append(msg)

        self.ui.write_text.clear()

    def getFriendList(self):
        # [{"name": "aaa"}]
        friendList = json.load(open(pathlib.Path(__file__).resolve().parent.parent.joinpath('friendlist.json'), 'r'))
        print(friendList)
        self.ui.tableWidget.setRowCount(0)
        self.ui.tableWidget.clearContents()
        self.ui.tableWidget.setHorizontalHeaderLabels(["好友列表"])

        for i in friendList:
            self.ui.tableWidget.insertRow(friendList.index(i))
            #self.ui.tableWidget.setItem(friendList.index(i), 0, QtWidgets.QTableWidgetItem(i["name"]))
            self.ui.tableWidget.setCellWidget(friendList.index(i), 0, QPushButton(text=i["name"]))

if __name__ == '__main__':
    app=QApplication(sys.argv)

    window=Window()
    window.ui.show()

    sys.exit(app.exec_())
